﻿using System.Collections.Generic;
using Entitas;
using System.Linq;
class EnemyReturnTospawnCommandSystem : ReactiveSystem<RequestEntity> ,ICleanupSystem
{
    RequestContext requestContext;
    EnemyContext enemyContext;
    CommandContext commandContext;
    public EnemyReturnTospawnCommandSystem(Contexts contexts) : base(contexts.request)
    {
        requestContext = contexts.request;
        enemyContext = contexts.enemy;
        commandContext = contexts.command;
    }

   
    protected override void Execute(List<RequestEntity> entities)
    {
        foreach (var e in entities)
        {
            ServiceManager.DebugMessageService.Print("checking battle movemennt request");
            var enemy = enemyContext.GetEntityWithName(e.returnToSpawnRequest.Owner);
            if (ServiceManager.PhysicsService.CastRayToCollider(enemy, enemy.position.value, e.returnToSpawnRequest.direction) == false)
                commandContext.CreateEntity().AddReturnToSpawnCommand(e.returnToSpawnRequest.Owner, e.returnToSpawnRequest.direction);
            else ServiceManager.DebugMessageService.Print("battle movement request denied");
        }
    }

    protected override bool Filter(RequestEntity entity)
    {
        return entity.hasReturnToSpawnRequest;
    }

    protected override ICollector<RequestEntity> GetTrigger(IContext<RequestEntity> context)
    {
        return context.CreateCollector(RequestMatcher.ReturnToSpawnRequest.Added());
    }

    public void Cleanup()
    {
        foreach(var e in requestContext.GetEntities().Where(r=> r.hasReturnToSpawnRequest==true))
        {
            e.Destroy();
        }
    }

}
